#include "qtscanner.h"
#include <QApplication>
#include <QMessageBox>
#include <QListWidgetItem>
#include <QHeaderView>
#include <QDebug>
#include <QStandardPaths>
#include <QProcessEnvironment>
#include <QFileInfoList>
#include <QRegularExpression>
#include <QSettings>
#include <QInputDialog>

// QtScanWorker 实现
QtScanWorker::QtScanWorker(QObject *parent)
    : QThread(parent)
{
}

void QtScanWorker::run()
{
    // 常见的Qt安装路径
    QStringList searchPaths;
    
    // 添加常见的Qt安装目录
    searchPaths << "C:/Qt"
                << "D:/Qt"
                << "E:/Qt"
                << "F:/Qt"
                << QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/Qt"
                << QProcessEnvironment::systemEnvironment().value("QTDIR", "").section('/', 0, -3); // 从QTDIR环境变量推导
    
    // 移除空路径
    searchPaths.removeAll("");
    
    // 扫描每个路径
    for (const QString &path : searchPaths) {
        if (QDir(path).exists()) {
            scanDirectory(path);
        }
    }
    
    emit scanFinished();
}

void QtScanWorker::scanDirectory(const QString &baseDir)
{
    QDir dir(baseDir);
    if (!dir.exists()) {
        return;
    }
    
    // 获取所有子目录
    QFileInfoList subdirs = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    
    for (const QFileInfo &subdir : subdirs) {
        QString subdirPath = subdir.absoluteFilePath();
        
        // 检查是否为版本号目录（如5.15.2）
        QRegularExpression versionRegex("^\\d+\\.\\d+");
        if (subdir.fileName().contains(versionRegex)) {
            // 在版本目录下查找编译器目录
            QDir versionDir(subdirPath);
            QFileInfoList compilerDirs = versionDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
            
            for (const QFileInfo &compilerDir : compilerDirs) {
                QString qtPath = compilerDir.absoluteFilePath();
                if (isValidQtInstallation(qtPath)) {
                    QString version = getQtVersion(qtPath);
                    QString compiler = getCompilerInfo(qtPath);
                    emit qtFound(qtPath, version, compiler);
                }
            }
        }
        // 直接检查是否为Qt安装目录
        else if (isValidQtInstallation(subdirPath)) {
            QString version = getQtVersion(subdirPath);
            QString compiler = getCompilerInfo(subdirPath);
            emit qtFound(subdirPath, version, compiler);
        }
        // 递归扫描子目录（限制深度避免过深扫描）
        else if (subdir.fileName() != "Tools" && subdir.fileName() != "Docs" && 
                 subdir.fileName() != "Examples" && subdir.fileName() != "Licenses") {
            scanDirectory(subdirPath);
        }
    }
}

bool QtScanWorker::isValidQtInstallation(const QString &qtPath)
{
    // 检查关键文件是否存在
    QDir qtDir(qtPath);
    
    // 检查bin目录和关键工具
    if (!qtDir.exists("bin") || !QFile::exists(qtPath + "/bin/windeployqt.exe")) {
        return false;
    }
    
    // 检查lib目录
    if (!qtDir.exists("lib")) {
        return false;
    }
    
    // 检查include目录
    if (!qtDir.exists("include")) {
        return false;
    }
    
    return true;
}

QString QtScanWorker::getQtVersion(const QString &qtPath)
{
    // 尝试从路径中提取版本信息
    QRegularExpression versionRegex("(\\d+\\.\\d+(?:\\.\\d+)?)");
    QRegularExpressionMatch match = versionRegex.match(qtPath);
    if (match.hasMatch()) {
        return match.captured(1);
    }
    
    // 如果路径中没有版本信息，尝试读取qmake输出
    QString qmakePath = qtPath + "/bin/qmake.exe";
    if (QFile::exists(qmakePath)) {
        // 这里可以执行qmake --version来获取版本，但为了简化先返回"Unknown"
        return "Unknown";
    }
    
    return "Unknown";
}

QString QtScanWorker::getCompilerInfo(const QString &qtPath)
{
    QString pathLower = qtPath.toLower();
    
    if (pathLower.contains("mingw")) {
        if (pathLower.contains("64")) {
            return "MinGW 64-bit";
        } else if (pathLower.contains("32")) {
            return "MinGW 32-bit";
        } else {
            return "MinGW";
        }
    } else if (pathLower.contains("msvc")) {
        if (pathLower.contains("2019")) {
            return "MSVC 2019";
        } else if (pathLower.contains("2017")) {
            return "MSVC 2017";
        } else if (pathLower.contains("2015")) {
            return "MSVC 2015";
        } else {
            return "MSVC";
        }
    } else if (pathLower.contains("clang")) {
        return "Clang";
    }
    
    return "Unknown";
}

// QtScanner 实现
QtScanner::QtScanner(QWidget *parent)
    : QDialog(parent)
    , m_mainLayout(nullptr)
    , m_buttonLayout(nullptr)
    , m_titleLabel(nullptr)
    , m_statusLabel(nullptr)
    , m_qtListWidget(nullptr)
    , m_progressBar(nullptr)
    , m_okButton(nullptr)
    , m_cancelButton(nullptr)
    , m_refreshButton(nullptr)
    , m_historyButton(nullptr)
    , m_scanWorker(nullptr)
{
    setupUI();
    connectSignals();
    loadHistory();
    
    // 创建扫描工作线程
    m_scanWorker = new QtScanWorker(this);
    
    // 连接工作线程信号
    connect(m_scanWorker, &QtScanWorker::qtFound, this, &QtScanner::onQtFound);
    connect(m_scanWorker, &QtScanWorker::scanFinished, this, &QtScanner::onScanFinished);
    
    // 自动开始扫描
    startScan();
}

QtScanner::~QtScanner()
{
    if (m_scanWorker && m_scanWorker->isRunning()) {
        m_scanWorker->quit();
        m_scanWorker->wait(3000); // 等待最多3秒
    }
}

QString QtScanner::getSelectedQtPath() const
{
    return m_selectedQtPath;
}

void QtScanner::setupUI()
{
    setWindowTitle("Qt安装扫描器");
    setModal(true);
    resize(600, 400);
    
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    
    // 标题标签
    m_titleLabel = new QLabel("正在扫描系统中的Qt安装...", this);
    m_titleLabel->setStyleSheet("font-size: 14px; font-weight: bold; margin: 10px;");
    m_mainLayout->addWidget(m_titleLabel);
    
    // 状态标签
    m_statusLabel = new QLabel("扫描中，请稍候...", this);
    m_mainLayout->addWidget(m_statusLabel);
    
    // 进度条
    m_progressBar = new QProgressBar(this);
    m_progressBar->setRange(0, 0); // 不确定进度
    m_mainLayout->addWidget(m_progressBar);
    
    // Qt列表
    m_qtListWidget = new QListWidget(this);
    m_qtListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    m_mainLayout->addWidget(m_qtListWidget);
    
    // 按钮布局
    m_buttonLayout = new QHBoxLayout();
    
    // 刷新按钮
    m_refreshButton = new QPushButton("刷新", this);
    m_buttonLayout->addWidget(m_refreshButton);
    
    // 历史记录按钮
    m_historyButton = new QPushButton("历史记录", this);
    m_buttonLayout->addWidget(m_historyButton);
    
    m_buttonLayout->addStretch(); // 添加弹性空间
    
    // 确定按钮
    m_okButton = new QPushButton("确定", this);
    m_okButton->setEnabled(false); // 初始禁用
    m_buttonLayout->addWidget(m_okButton);
    
    // 取消按钮
    m_cancelButton = new QPushButton("取消", this);
    m_buttonLayout->addWidget(m_cancelButton);
    
    m_mainLayout->addLayout(m_buttonLayout);
}

void QtScanner::connectSignals()
{
    connect(m_qtListWidget, &QListWidget::itemSelectionChanged, this, &QtScanner::onSelectionChanged);
    connect(m_okButton, &QPushButton::clicked, this, &QtScanner::onOkClicked);
    connect(m_cancelButton, &QPushButton::clicked, this, &QtScanner::onCancelClicked);
    connect(m_refreshButton, &QPushButton::clicked, this, &QtScanner::onRefreshClicked);
    connect(m_historyButton, &QPushButton::clicked, this, &QtScanner::onHistoryClicked);
}

void QtScanner::startScan()
{
    // 清空列表
    m_qtListWidget->clear();
    m_selectedQtPath.clear();
    
    // 更新UI状态
    m_titleLabel->setText("正在扫描系统中的Qt安装...");
    m_statusLabel->setText("扫描中，请稍候...");
    m_progressBar->setVisible(true);
    m_okButton->setEnabled(false);
    m_refreshButton->setEnabled(false);
    
    // 启动扫描
    if (m_scanWorker && !m_scanWorker->isRunning()) {
        m_scanWorker->start();
    }
}

void QtScanner::onQtFound(const QString &qtPath, const QString &version, const QString &compiler)
{
    // 创建列表项
    QListWidgetItem *item = new QListWidgetItem(m_qtListWidget);
    
    // 设置显示文本
    QString displayText = QString("Qt %1 (%2)\n%3").arg(version, compiler, qtPath);
    item->setText(displayText);
    
    // 存储完整路径作为数据
    item->setData(Qt::UserRole, qtPath);
    
    // 设置工具提示
    item->setToolTip(qtPath);
    
    m_qtListWidget->addItem(item);
    
    // 更新状态
    m_statusLabel->setText(QString("已找到 %1 个Qt安装").arg(m_qtListWidget->count()));
}

void QtScanner::onScanFinished()
{
    // 更新UI状态
    m_progressBar->setVisible(false);
    m_refreshButton->setEnabled(true);
    
    if (m_qtListWidget->count() > 0) {
        m_titleLabel->setText("请选择要使用的Qt安装:");
        m_statusLabel->setText(QString("扫描完成！找到 %1 个Qt安装").arg(m_qtListWidget->count()));
        
        // 自动选择第一个Qt安装
        if (m_qtListWidget->count() > 0) {
            m_qtListWidget->setCurrentRow(0);
        }
    } else {
        m_titleLabel->setText("未找到Qt安装");
        m_statusLabel->setText("未在常见位置找到Qt安装。\n请检查Qt是否已正确安装，或尝试手动指定Qt路径。");
        m_okButton->setEnabled(false);
        
        // 显示详细的扫描结果消息
        QMessageBox::information(this, "扫描完成", 
            "扫描完成，但未找到有效的Qt安装。\n\n"
            "扫描的路径包括：\n"
            "• C:/Qt\n"
            "• D:/Qt\n"
            "• E:/Qt\n"
            "• F:/Qt\n"
            "• 用户主目录/Qt\n"
            "• 系统环境变量QTDIR指定的路径\n\n"
            "请确保Qt已正确安装，或使用历史记录功能选择之前使用过的Qt路径。");
    }
}

void QtScanner::onSelectionChanged()
{
    QListWidgetItem *currentItem = m_qtListWidget->currentItem();
    if (currentItem) {
        m_selectedQtPath = currentItem->data(Qt::UserRole).toString();
        m_okButton->setEnabled(true);
    } else {
        m_selectedQtPath.clear();
        m_okButton->setEnabled(false);
    }
}

void QtScanner::onOkClicked()
{
    if (!m_selectedQtPath.isEmpty()) {
        // 保存到历史记录
        saveToHistory(m_selectedQtPath);
        
        // 显示确认消息
        QMessageBox::information(this, "选择确认", 
            QString("已选择Qt安装路径：\n%1\n\n该路径将被保存到历史记录中，并用于更新配置文件。").arg(m_selectedQtPath));
        
        accept(); // 关闭对话框并返回Accepted
    }
}

void QtScanner::onCancelClicked()
{
    reject(); // 关闭对话框并返回Rejected
}

void QtScanner::onRefreshClicked()
{
    startScan();
}

void QtScanner::onHistoryClicked()
{
    showHistoryDialog();
}

void QtScanner::onHistoryItemSelected(const QString &qtPath)
{
    m_selectedQtPath = qtPath;
    
    // 在列表中查找并选中对应项
    for (int i = 0; i < m_qtListWidget->count(); ++i) {
        QListWidgetItem *item = m_qtListWidget->item(i);
        if (item->data(Qt::UserRole).toString() == qtPath) {
            m_qtListWidget->setCurrentItem(item);
            break;
        }
    }
    
    // 如果列表中没有找到，添加一个新项
    if (m_qtListWidget->currentItem() == nullptr || 
        m_qtListWidget->currentItem()->data(Qt::UserRole).toString() != qtPath) {
        
        // 验证路径是否仍然有效
        if (QDir(qtPath).exists() && QFile::exists(qtPath + "/bin/windeployqt.exe")) {
            QListWidgetItem *item = new QListWidgetItem(m_qtListWidget);
            
            // 获取版本和编译器信息
            QString version = "Unknown";
            QString compiler = "Unknown";
            
            QRegularExpression versionRegex("(\\d+\\.\\d+(?:\\.\\d+)?)");
            QRegularExpressionMatch match = versionRegex.match(qtPath);
            if (match.hasMatch()) {
                version = match.captured(1);
            }
            
            QString pathLower = qtPath.toLower();
            if (pathLower.contains("mingw")) {
                if (pathLower.contains("64")) {
                    compiler = "MinGW 64-bit";
                } else if (pathLower.contains("32")) {
                    compiler = "MinGW 32-bit";
                } else {
                    compiler = "MinGW";
                }
            } else if (pathLower.contains("msvc")) {
                compiler = "MSVC";
            }
            
            QString displayText = QString("Qt %1 (%2) [历史记录]\n%3").arg(version, compiler, qtPath);
            item->setText(displayText);
            item->setData(Qt::UserRole, qtPath);
            item->setToolTip(qtPath);
            
            m_qtListWidget->addItem(item);
            m_qtListWidget->setCurrentItem(item);
        }
    }
    
    m_okButton->setEnabled(true);
}

void QtScanner::loadHistory()
{
    QSettings settings("QtDeploy", "QtScanner");
    m_historyPaths = settings.value("historyPaths", QStringList()).toStringList();
    
    // 移除重复项并限制历史记录数量
    m_historyPaths.removeDuplicates();
    while (m_historyPaths.size() > 10) {
        m_historyPaths.removeLast();
    }
}

void QtScanner::saveToHistory(const QString &qtPath)
{
    if (qtPath.isEmpty()) {
        return;
    }
    
    // 如果已存在，先移除
    m_historyPaths.removeAll(qtPath);
    
    // 添加到开头
    m_historyPaths.prepend(qtPath);
    
    // 限制历史记录数量
    while (m_historyPaths.size() > 10) {
        m_historyPaths.removeLast();
    }
    
    // 保存到设置
    QSettings settings("QtDeploy", "QtScanner");
    settings.setValue("historyPaths", m_historyPaths);
    settings.sync();
}

void QtScanner::showHistoryDialog()
{
    if (m_historyPaths.isEmpty()) {
        QMessageBox::information(this, "历史记录", "暂无历史记录");
        return;
    }
    
    // 创建历史记录选择对话框
    QDialog historyDialog(this);
    historyDialog.setWindowTitle("选择历史Qt路径");
    historyDialog.setModal(true);
    historyDialog.resize(500, 300);
    
    QVBoxLayout *layout = new QVBoxLayout(&historyDialog);
    
    QLabel *label = new QLabel("请选择一个历史Qt路径:", &historyDialog);
    layout->addWidget(label);
    
    QListWidget *historyList = new QListWidget(&historyDialog);
    
    // 添加历史记录项
    for (const QString &path : m_historyPaths) {
        // 验证路径是否仍然有效
        if (QDir(path).exists() && QFile::exists(path + "/bin/windeployqt.exe")) {
            QListWidgetItem *item = new QListWidgetItem(historyList);
            
            // 获取版本和编译器信息
            QString version = "Unknown";
            QString compiler = "Unknown";
            
            QRegularExpression versionRegex("(\\d+\\.\\d+(?:\\.\\d+)?)");
            QRegularExpressionMatch match = versionRegex.match(path);
            if (match.hasMatch()) {
                version = match.captured(1);
            }
            
            QString pathLower = path.toLower();
            if (pathLower.contains("mingw")) {
                if (pathLower.contains("64")) {
                    compiler = "MinGW 64-bit";
                } else if (pathLower.contains("32")) {
                    compiler = "MinGW 32-bit";
                } else {
                    compiler = "MinGW";
                }
            } else if (pathLower.contains("msvc")) {
                compiler = "MSVC";
            }
            
            QString displayText = QString("Qt %1 (%2)\n%3").arg(version, compiler, path);
            item->setText(displayText);
            item->setData(Qt::UserRole, path);
            item->setToolTip(path);
            
            historyList->addItem(item);
        }
    }
    
    layout->addWidget(historyList);
    
    // 按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *selectButton = new QPushButton("选择", &historyDialog);
    QPushButton *cancelButton = new QPushButton("取消", &historyDialog);
    
    selectButton->setEnabled(false);
    
    buttonLayout->addStretch();
    buttonLayout->addWidget(selectButton);
    buttonLayout->addWidget(cancelButton);
    
    layout->addLayout(buttonLayout);
    
    // 连接信号
    connect(historyList, &QListWidget::itemSelectionChanged, [selectButton, historyList]() {
        selectButton->setEnabled(historyList->currentItem() != nullptr);
    });
    
    connect(selectButton, &QPushButton::clicked, [&historyDialog]() {
        historyDialog.accept();
    });
    
    connect(cancelButton, &QPushButton::clicked, [&historyDialog]() {
        historyDialog.reject();
    });
    
    connect(historyList, &QListWidget::itemDoubleClicked, [&historyDialog]() {
        historyDialog.accept();
    });
    
    // 显示对话框
    if (historyDialog.exec() == QDialog::Accepted) {
        QListWidgetItem *selectedItem = historyList->currentItem();
        if (selectedItem) {
            QString selectedPath = selectedItem->data(Qt::UserRole).toString();
            onHistoryItemSelected(selectedPath);
        }
    }
}